package com.ideaaedi.springcloud.jd.commonspring.interceptor;

import com.alibaba.fastjson2.JSON;
import com.ideaaedi.springcloud.jd.commonds.constant.BaseConstant;
import com.ideaaedi.springcloud.jd.commonds.feign.CrossMicroServiceTransDataDTO;
import com.ideaaedi.springcloud.jd.commonds.util.CommonUtil;
import com.ideaaedi.springcloud.jd.commonspring.util.JdContextUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * feign请求拦截器
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2021.0.1.A
 */
@Slf4j
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {
    
    @Value("${spring.application.name:}")
    private String applicationName;
    
    /**
     * 1. 将jwt-token传递到下一个微服务
     * 2. 将traceId传递到下一个微服务
     * 3. 跨微服务请求
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request = JdContextUtil.getHttpServletRequest();
        if (request == null) {
            log.info("request is null. skip FeignRequestInterceptor#apply.");
            return;
        }
        // jwt-token
        String traceId = CommonUtil.getTraceIdMdcFirst(request.getRequestURI(), request.getHeader(BaseConstant.TRACE_ID));
        requestTemplate.header(BaseConstant.JWT_TOKEN_KEY, request.getHeader(BaseConstant.JWT_TOKEN_KEY));
        // traceId
        requestTemplate.header(BaseConstant.TRACE_ID, traceId);
        // cross micro service request
        requestTemplate.header(BaseConstant.IF_CROSS_MICRO_SERVICE_REQUEST, Boolean.TRUE.toString());
        CrossMicroServiceTransDataDTO crossMicroServiceTransData = new CrossMicroServiceTransDataDTO();
        crossMicroServiceTransData.setUserId(JdContextUtil.currUserId());
        crossMicroServiceTransData.setTenant(JdContextUtil.currUserTenant());
        crossMicroServiceTransData.setFromMicroService(applicationName);
        crossMicroServiceTransData.setReadDataScopePaths(JdContextUtil.currUserDataScopeRead());
        crossMicroServiceTransData.setUpdateDataScopePaths(JdContextUtil.currUserDataScopeUpdate());
        String transData;
        try {
            transData = URLEncoder.encode(JSON.toJSONString(crossMicroServiceTransData), StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        requestTemplate.header(BaseConstant.CROSS_MICRO_SERVICE_TRANS_DATA, transData);
    }
}
